import requests
import base64

# 设置 API 请求的参数
owner = "KeepHeartbeat"  # 仓库所有者的用户名
repo = "file"  # 仓库名称
path = "image/tes1t.img"  # 文件在仓库中的路径
token = "e92fb28fd96cf10ea12f727d5a861a9f"  # 您生成的访问令牌
message = "Add file via API"  # 提交信息
branch = "master"  # 要将文件上传到哪个分支

# 读取文件内容并将其转换为 Base64 编码格式
with open("C:\\Users\\Ru\\Pictures\\111.jpg", "rb") as f:
    content = base64.b64encode(f.read()).decode("utf-8")

# 构建 API 请求的 URL 和数据
url = f"https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}"
data = {
    "message": message,
    "content": content,
    "branch": branch
}

# 设置 API 请求的标头
headers = {
    "Authorization": f"token {token}",
    "Content-Type": "application/json"
}

# 发送 API 请求
response = requests.post(url, json=data, headers=headers)

# 处理 API 响应
if response.ok:
    print("文件上传成功！")
    print(response.text)
else:
    print(f"文件上传失败：{response.text}")

res = {
    "content": {
        "name": "tes1t.img",
        "path": "image/tes1t.img",
        "size": 305094,
        "sha": "cc56ece775cb89972a9013e27cb29b7704bbc412",
        "type": "file",
        "url": "https://gitee.com/api/v5/repos/KeepHeartbeat/file/contents/image/tes1t.img",
        "html_url": "https://gitee.com/KeepHeartbeat/file/blob/master/image/tes1t.img",
        "download_url": "https://gitee.com/KeepHeartbeat/file/raw/master/image/tes1t.img",
        "_links": {
            "self": "https://gitee.com/api/v5/repos/KeepHeartbeat/file/contents/image/tes1t.img",
            "html": "https://gitee.com/KeepHeartbeat/file/blob/master/image/tes1t.img"
        }
    },
    "commit": {
        "sha": "06ddea919da2fc67aece62e8eeac708fb0b8c3e3",
        "author": {
            "name": "游瑞",
            "date": "2023-05-12T08:43:07+00:00",
            "email": "12920808+KeepHeartbeat@user.noreply.gitee.com"
        },
        "committer": {
            "name": "Gitee",
            "date": "2023-05-12T08:43:07+00:00",
            "email": "noreply@gitee.com"
        },
        "message": "Add file via API",
        "tree": {
            "sha": "3c1f8c349068bfedfb4f22a1fa26cd2d9f973ae2",
            "url": "https://gitee.com/api/v5/repos/KeepHeartbeat/file/git/trees/3c1f8c349068bfedfb4f22a1fa26cd2d9f973ae2"
        },
        "parents": [
            {
                "sha": "174249ebb66514349d834779edeb4c30dd8ac89e",
                "url": "https://gitee.com/api/v5/repos/KeepHeartbeat/file/commits/174249ebb66514349d834779edeb4c30dd8ac89e"
            }
        ]
    }
}
